import time
from transitions import Machine
class WaterHeater:
    states = ['off', 'on', 'broken']
    def __init__(self):
        """
        假设水烧开3次就会烧坏
        这里没有具体说明水的使用情况，暂定为总是有水
        """
        self.machine = Machine(model=self, states=self.states, initial='off')
        self.machine.add_transition(trigger='turn_on',source='off',dest='on',conditions=["if_temperature_below_20","has_water"],unless="is_night",after="turn_on_call")
        self.machine.add_transition(trigger='turn_off',source= 'on',dest='off',conditions=["if_temperature_above_100"],after="turn_off_call")
        self.machine.add_transition(trigger='broken',source= 'on',dest='broken',conditions=["is_broken"],after="broken_call")
        self.machine.add_transition(trigger='keep_off',source= 'off',dest='off',conditions=["is_night"])
        self.temperature = 20
        self.age=3
        self.water_level=True

    def turn_on_call(self):
        print("电源已经开启")
        self.age -= 1
        """
        每次开启寿命减少
        """
        self.broken()
    def turn_off_call(self):
        print("电源已经关闭")
    def broken_call(self):
        print("水箱已损坏")

    def if_temperature_below_20(self):
        return self.temperature <= 20
    def has_water(self):
        return self.water_level
    def if_temperature_above_100(self):
        return self.temperature >= 100
    def is_night(self):
        current_hour = time.localtime().tm_hour
        return current_hour >= 23 or current_hour < 7
    def is_broken(self):
        return self.age<0
    def run(self):
        while True:
            if self.state=="on":
                time.sleep(1)
                self.temperature+=20
                print("当前温度是",self.temperature)
                self.turn_off()
            elif self.state=="off":
                time.sleep(1)
                if self.temperature>=40:
                    self.temperature-=20
                print("当前温度是",self.temperature)
                self.keep_off()
                self.turn_on()
            else :
                break
water_heater = WaterHeater()
water_heater.run()